const { User, Resource } = require('../models');
const cozeClient = require('../utils/cozeClient');
const eduSystemClient = require('../utils/eduSystemClient');

/**
 * 生成练习题
 * @route POST /api/exercise/generate
 */
const generateExercise = async (req, res, next) => {
  try {
    const { knowledgePointIds, questionTypes, difficultyRatio, userId = 1 } = req.body;
    
    // 1. 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 获取知识点详情
    const knowledgePoints = [];
    for (const knowledgePointId of knowledgePointIds) {
      const detail = await eduSystemClient.getKnowledgePointDetail(knowledgePointId);
      knowledgePoints.push(detail);
    }
    
    // 3. 构建Coze智能体输入参数
    const cozeParams = {
      knowledgePoints: knowledgePoints.map(kp => ({
        id: kp.id,
        name: kp.name,
        description: kp.description,
        difficulty: kp.difficulty
      })),
      questionTypes: questionTypes || ['选择题', '填空题', '简答题'],
      difficultyRatio: difficultyRatio || { easy: 0.3, medium: 0.5, hard: 0.2 },
      outputFormat: 'JSON' // 请求结构化输出
    };
    
    // 4. 调用Coze智能体生成练习题
    const exerciseResult = await cozeClient.callBot('exerciseBot', cozeParams);
    
    // 5. 校验重复题（与历史数据对比）
    // 获取用户历史练习题资源
    const historicalExercises = await Resource.findAll({
      where: {
        userId,
        type: 'exercise'
      },
      order: [['generateTime', 'DESC']],
      limit: 10 // 只检查最近10个练习题资源
    });
    
    // 简单去重逻辑（实际项目中可能需要更复杂的文本相似度比较）
    const existingQuestions = new Set();
    historicalExercises.forEach(resource => {
      if (resource.content && resource.content.exercises) {
        resource.content.exercises.forEach(exercise => {
          existingQuestions.add(exercise.question.trim());
        });
      }
    });
    
    // 过滤掉重复题目
    const uniqueExercises = exerciseResult.exercises.filter(exercise => {
      return !existingQuestions.has(exercise.question.trim());
    });
    
    // 6. 保存到资源表
    const exerciseContent = {
      exercises: uniqueExercises,
      knowledgePoints: knowledgePoints.map(kp => kp.name),
      questionTypes,
      difficultyRatio,
      generatedAt: new Date().toISOString(),
      totalCount: uniqueExercises.length
    };
    
    const resource = await Resource.create({
      userId,
      type: 'exercise',
      content: exerciseContent,
      isSaved: false
    });
    
    // 7. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        exercises: uniqueExercises,
        resourceId: resource.id,
        originalCount: exerciseResult.exercises.length,
        uniqueCount: uniqueExercises.length
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 导出练习题为PDF
 * @route GET /api/exercise/export/:resourceId
 */
const exportExercise = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 1. 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: 'exercise'
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '练习题资源不存在'
      });
    }
    
    // 2. 生成PDF（实际项目中应该调用PDF生成库）
    // 这里模拟PDF生成，返回成功消息
    
    // 模拟PDF生成延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 3. 返回结果
    res.json({
      code: 200,
      success: true,
      message: 'PDF导出功能在实际项目中实现',
      data: {
        resourceId,
        fileName: `练习题_${resourceId}.pdf`,
        // 实际项目中应该返回PDF文件下载链接
        downloadUrl: `/downloads/exercises/${resourceId}.pdf`
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取练习题详情
 * @route GET /api/exercise/:resourceId
 */
const getExerciseDetail = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: 'exercise'
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '练习题资源不存在'
      });
    }
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        resourceId: resource.id,
        userId: resource.userId,
        exerciseContent: resource.content,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  generateExercise,
  exportExercise,
  getExerciseDetail
};